package com.agu.mgt.code.service;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.agu.utils.Query;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import com.agu.mgt.code.dao.CodTableDao;
import com.agu.code.CodeUtils;
import com.agu.entity.code.CodTableEntity;
import com.agu.mgt.code.service.CodTableService;
import com.agu.mgt.sys.dto.CodeVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;


@Service("codTableService")
@Transactional(readOnly = true)
public class CodTableService{
	@Autowired
	private CodTableDao codTableDao;
	
	
	public CodTableEntity queryObject(Long tableId){
		return codTableDao.queryObject(tableId);
	}
	
	
	public List<CodTableEntity> queryList(Map<String, Object> map){
		return codTableDao.queryList(map);
	}

    
	public Page<CodTableEntity> queryPageList(Query query){
	    PageHelper.startPage(query.getPage(), query.getLimit());
	    return codTableDao.queryPageList(query);
	}
	

	@Transactional
	public void updateTableComments(CodTableEntity codTable){
		codTableDao.updateTableComments(codTable);
	}
	
	public byte[] generatorCode(CodeVo cc) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		for (String tableName : cc.getTables()) {
			// 查询表信息
			Map<String, String> table = queryTable(tableName);
			// 查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			// 生成代码
			CodeUtils.generatorCode(table, columns, zip, cc);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
	
	public Map<String, String> queryTable(String tableName) {
		return codTableDao.queryTable(tableName);
	}

	public List<Map<String, String>> queryColumns(String tableName) {
		
		List<Map<String, String>> list = codTableDao.queryColumns(tableName);
		
		for(Map<String, String> map : list) {
			String columnComment = map.get("columnComment");
			if(StringUtils.isNotBlank(columnComment)) {
				String[] comments = columnComment.split("\\|");
				map.put("shortComment", comments[0]);
			}
		}
		return list;
	}
}
